package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.example.myapplication.bean.FaceBean;
import com.example.myapplication.bean.LoadImageBean;
import com.example.myapplication.net.Common;
import com.example.myapplication.utils.AESEncryptUtils;
import com.example.myapplication.utils.Constants;
import com.example.myapplication.utils.DateUtil;
import com.example.myapplication.utils.OkHttp3_0Utils;
import com.example.myapplication.utils.QZXTools;
import com.example.myapplication.utils.SharedPreferenceUtil;
import com.example.myapplication.utils.ThreadPool;
import com.hjq.toast.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.sanstar.baiduFacePay.BaiduFacePay;
import com.sanstar.baiduFacePay.callback.IBaiduFaceCB;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.example.myapplication.net.Common.BaseUrl;

public class LoadImageTestActivity extends BaseActivity {

    private final static String TAG = "LoadImageActivity";

    MyHandler mHandler;

    HashMap<String, Object> map = new HashMap<>();
    public boolean initFace = false;
    private Integer currentPage = 1;
    private Integer totalPage = 1;
    private Integer pageSize = 3;
    private TextView tv_name;
    private ScrollView sv;
    private TextView tv_times;

    private class MyHandler extends Handler {
        private WeakReference<Activity> activityWeakReference;

        public MyHandler(Activity activity) {
            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Activity activity = activityWeakReference.get();
            Log.d(TAG, "msg = " + msg.what);
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        BaiduFacePay.getInstance().preloadSdkEnv(map, new IBaiduFaceCB() {
                            @Override
                            public void response(Map info) {
                                String msg = (String) info.get("return_msg");
                                int code = (int) info.get("return_code");
                                QZXTools.logD(TAG, "preloadSdkEnv msg = " + msg + ", code = " + code);

                                if (msg.equals("SUCC")) {
                                    mHandler.sendEmptyMessage(2);
                                    initFace = true;
                                    baseHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            tv_name.append(DateUtil.yearsTime() + "  百度人脸识加载环境成功\n");
                                            downloadCompleted(null);
                                        }
                                    }, 1000 * 8);
                                }
                            }
                        });
                        break;

                    default:
                        break;
                }
            }
        }
    }

    // 1再第一步要删除所有的图片
    // 2开始 下载 图片，比如 50张图片,只有 42张 是有效的 ，需要告诉 给后端 8张图片是由问题的 同时本地要删除这8张图片
    // 3 接着就是开始出处理这 42张图片 ，循环 一张一张的处理，处理成功后就把本张图片 一张一张的 删除，有可能 42张图片 只有 40张是有效的 这也是要提交给后端
    // 4. 记录两张不能生成的图片提交给后端，同时本地也删除 这两个图片是由问题的
    // 5. 处理完成后，就接着处理 第 2页，数据 ，定时任务 ，一直再运行，要想能正常运行，必须等第4步运行完成
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load_image);
        tv_name = findViewById(R.id.tv_name);
        sv = findViewById(R.id.sv);
        tv_times = findViewById(R.id.tv_times);
        addActivity(this);

        times = 0;
        mHandler = new MyHandler(this);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                init();
            }
        }, 1000 * 30);

        //下载图片到本地
        findViewById(R.id.down_image).setOnClickListener((view) -> {
            init();

        });

        SwitchButton btn_voice_switch = findViewById(R.id.btn_voice_switch);
        findViewById(R.id.tv_out_login).setOnClickListener(v -> {
            SharedPreferenceUtil.getInstance(MyAPP.getInstance()).setString("token", "");
            Intent intent = new Intent(LoadImageTestActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();

        });

        btn_voice_switch.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    //正式环境
                    ToastUtils.show("开启了正式环境地址\n5秒后自动退出app生效");
                } else {
                    //测试环境
                    ToastUtils.show("开启了测试环境地址\n5秒后自动退出app生效");
                }
                SharedPreferenceUtil.getInstance(MyAPP.getInstance()).setBoolean("DEVELOPMENT_ENVIRONMENT", isChecked);
                SharedPreferenceUtil.getInstance(MyAPP.getInstance()).setString("token", "");
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finishAll();
                        android.os.Process.killProcess(android.os.Process.myPid());

                    }
                }, 1000 * 5);
            }
        });


        boolean development_environment = SharedPreferenceUtil.getInstance(MyAPP.getInstance()).getBoolean("DEVELOPMENT_ENVIRONMENT", true);
        if (development_environment) {
            btn_voice_switch.setChecked(true);
        } else {
            btn_voice_switch.setChecked(false);
        }


    }

    private void init() {
        BaiduFacePay.getInstance().initBaiduFace(this, map, new IBaiduFaceCB() {
            @Override
            public void response(Map info) {
                if (info == null) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            tv_name.append(DateUtil.yearsTime() + "     百度人脸识初始化失败\n");
                        }
                    }, 100);

                    return;
                }
                String msg = (String) info.get("return_msg");
                int code = (int) info.get("return_code");
                if (msg == null || !msg.equals("SUCC")) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            tv_name.append(DateUtil.yearsTime() + "     百度人脸识初始化失败\n");
                        }
                    }, 100);
                    //  new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                }
                QZXTools.logD(TAG, "init msg = " + msg + ", code = " + code);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_name.append(DateUtil.yearsTime() + "     百度人脸识初始化成功\n");
                    }
                }, 100);

                //1再第一步要删除所有的图片
             //   deleteFile();

                mHandler.sendEmptyMessage(1);
            }
        });
    }


    int times = 0;

    @Override
    protected void handleActMessage(Message msg) {
        super.handleActMessage(msg);
        switch (msg.what) {
            case Common.Interface_err:
                String info = (String) msg.obj;
                ToastUtils.show(info);
                //显示 没有授权
                // MessageDialog.show("标题", info, "确定");
                mHandler.post(() -> tv_name.append(DateUtil.yearsTime() + "      网络请求失败" + "等待5分钟后再次调用获取图片接口....errInfo=" + info + "\n"));


                times++;
                break;
            case Common.Interface_success:
                LoadImageBean adviceActivationBean = (LoadImageBean) msg.obj;

                LoadImageBean.DataDTO dataDTO = adviceActivationBean.getData();
                if (dataDTO != null) {
                    List<LoadImageBean.DataDTO.RecordsDTO> records = dataDTO.getRecords();
                    //获取当前页
                    currentPage = dataDTO.getCurrent();
                    totalPage = dataDTO.getTotal();


                    break;

                }
        }


    }

    long time = 0;
    //当前图片下载完成
    List<String> imageSize = new ArrayList<>();

    private void downloadCompleted(List<String> size) {
        baseHandler.postDelayed(() -> {
            tv_name.append(DateUtil.yearsTime() + "     开始处理把图片生成特征码\n");
            //开始处理把图片生成特征码
            // 3 接着就是开始出处理这 42张图片 ，循环 一张一张的处理，处理成功后就把本张图片 一张一张的 删除，有可能 42张图片 只有 40张是有效的 这也是要提交给后端
            // 4. 记录两张不能生成的图片提交给后端，同时本地也删除 这两个图片是由问题的
            startFeatureCode(imageSize);

        }, 1);

    }

    //开始生成成特征码
    private void startFeatureCode(List<String> imageSize) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "tiantian");
        List<String> filesAllName = QZXTools.getFilesAllName(appDir);
        imageSize.addAll(filesAllName);
        Log.i(TAG, "startFeatureCode: " + imageSize.size());
        if (initFace) {
            ThreadPool.singleExecute(new Runnable() {
                @Override
                public void run() {
                    for (String path : imageSize) {
                        try {
                            Thread.sleep(10);
                            startLoadImage(path, imageSize.size());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        } else {
            baseHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tv_name.append("             人脸识别初始化失败\n");
                }
            }, 1000);
        }
    }

    //要是处理失败也要处理  可能在调用百度的sdk 报错了，导致不知道哪个图片有问题
    private volatile int loadImageCount = 0;
    private volatile boolean isCompleted = false;

    private synchronized void startLoadImage(String path, int size) {
        if (path.equals("/storage/emulated/0/tiantian/21066.jpg")){
            HashMap<String, Object> map = new HashMap<>();
            map.put("pictureURL", path);
            QZXTools.logD(TAG + "path=" + path);
            try {
                BaiduFacePay.getInstance().getFaceFeature(map, new IBaiduFaceCB() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void response(Map map) {
                        String msg = (String) map.get("return_msg");
                        int code = (int) map.get("return_code");
                        Log.d(TAG, "get feature msg = " + msg + ", code = " + code);
                        byte[] feature = (byte[]) map.get("feature");
                        int index = path.lastIndexOf("/");
                        String currentPath = path.substring(index + 1, path.length() - 4);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                tv_name.append(DateUtil.yearsTime() + "           开始处理生成特征值的当前图片的memberID =" + currentPath + "\n");

                                tv_name.append(DateUtil.yearsTime() + "           开始处理生成特征值的当前图片的信息 =" + msg + "\n");
                                tv_name.append(DateUtil.yearsTime() + "           开始处理生成特征值的当前图片的code =" + code + "\n");
                            }
                        });

                        if (feature != null) {
                            Log.d(TAG, "feature = " + Base64.getEncoder().encodeToString(feature));

                            Log.d(TAG, "response: currentPath=" + currentPath);
                            FaceBean faceBean = new FaceBean();
                            faceBean.setFeatureData(Base64.getEncoder().encodeToString(feature));

                            faceBean.setMemberId(Integer.valueOf(currentPath));


                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    tv_name.append(DateUtil.yearsTime() + "           当前的图片memberID =" + currentPath + "特征值通过百度api生成成功 特征值=" + Base64.getEncoder().encodeToString(feature) + "\n");
                                    //shengcheng特征值完成 上传服务器
                                    eigenvaluesCompleted(faceBean, path);
                                }
                            }, 1);

                        } else {
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    tv_name.append(DateUtil.yearsTime() + "           生成特征码失败当前memberID=" + currentPath + "\n");

                                    //删除当前图片
//                                File file = new File(path);
//                                if (file.exists()) {
//                                    boolean delete = file.delete();
//                                    if (delete) {
//                                        tv_name.append(DateUtil.yearsTime()+"          删除生成特征码失败的,当前图片的memberId= " + currentPath + "\n");
//                                    }
//                                }
                                }
                            }, 10);
                        }
                        ++loadImageCount;

                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (loadImageCount == size) {
                                    //说明当前的图片已经处理完成了
                                    loadImageCount = 0;
                                    tv_name.append(DateUtil.yearsTime() + "         当前页的数据处理完成\n");
                                    isCompleted = true;
                                    tv_name.append(DateUtil.yearsTime() + "         等待1分钟后再次获取图片\n");

                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            time++;
                                            tv_name.append(DateUtil.yearsTime() + "                //////////////////////////////////////////////////////////////////////" +
                                                    "/////////////////////////////////////////////////////////////////////////////////////////////////////////////" +
                                                    "//////////////////////////////////////////////////////////////////////////////////////////////////////////\n");
                                            tv_name.append(DateUtil.yearsTime() + "           说明当前的图片已经处理完成了  开始" + time + "次下载当前图片\n");

                                        }
                                    }, 1000 * 60);


                                }
                            }
                        }, 1000);


                    }
                });
            } catch (Exception e) {
                //  e.fillInStackTrace();
            }
        }


    }

    /**
     * 生成特征值完成
     *
     * @param faceBean
     * @param path
     */
    private void eigenvaluesCompleted(FaceBean faceBean, String path) {
        String url = Common.UPDATA_FACE_IMAGE;
        try {
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("memberId", faceBean.getMemberId() + "");
            jsonObject.put("featureData", faceBean.getFeatureData());
            jsonArray.put(jsonObject);

            String encrypt = AESEncryptUtils.encrypt(jsonArray.toString(), Constants.DECRYPT_KEY);
            OkHttp3_0Utils.getInstance().asyncBodyEncryptStringOkHttp(url, encrypt, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    Message message = Message.obtain();
                    message.what = Common.Interface_err;
                    message.obj = "当前服务不可用" + e.getMessage();
                    baseHandler.sendMessage(message);

                    baseHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            tv_name.append(DateUtil.yearsTime() + "           上传特征值失败,当前图片的memberId= " + faceBean.getMemberId() + "\n");
                        }
                    });
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String content = response.body().string();
                    QZXTools.logE("onResponse: " + content, null);

                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(content);
                        int code = jsonObject.optInt("code");
                        String msg = jsonObject.optString("message");
                        if (code == 200) {

                            baseHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    tv_name.append(DateUtil.yearsTime() + "           上传特征值成功,当前图片的memberId= " + faceBean.getMemberId() + "\n" + "特征值上传服务器成功=" + faceBean.getFeatureData() + "\n");
                                    //删除当前图片
                                    File file = new File(path);
                                    if (file.exists()) {
                                        boolean delete = file.delete();
                                        if (delete) {
                                            tv_name.append(DateUtil.yearsTime() + "           删除上传特征值成功的,当前图片的memberId= " + faceBean.getMemberId() + "\n");
                                        }
                                    }
                                }
                            });

                        } else {
                            Message message = Message.obtain();
                            message.what = Common.Interface_err;
                            message.obj = msg;
                            baseHandler.sendMessage(message);
                            baseHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    tv_name.append(DateUtil.yearsTime() + "           上传特征值失败,当前图片的memberId= " + faceBean.getMemberId() + "\n");
                                }
                            });

                        }
                    } catch (Exception e) {
                        Message message = Message.obtain();
                        message.what = Common.Interface_err;
                        message.obj = "当前服务获取数据失败" + e.getMessage();
                        baseHandler.sendMessage(message);

                        baseHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                tv_name.append(DateUtil.yearsTime() + "           上传特征值失败,当前图片的memberId= " + faceBean.getMemberId() + "\n");
                            }
                        });
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ThreadPool.closeExecute();
        removeActivity(this);
        BaiduFacePay.getInstance().releaseBaiduFace(this);
        android.os.Process.killProcess(android.os.Process.myPid());

        Glide.with(this)
                .load("")
                .into(new ImageButton(this));

        EventBus.getDefault().post(new ImageButton(this));

    }
}
